#! /usr/bin/php
<?php
/*
 * 自动启动任务策略
 * @since 1.0 2015-11-09 SoChishun <14507247@qq.com>
 * @remark 启动 php -f /var/www/html/xcall_deamon/strategy_timer.php
 * @remark chkconfig /var/www/html/xcall_deamon/strategy_timer.php
 */
set_time_limit(0);

$config = include '/var/www/html/xcall/Application/XCall/Conf/config.php';

// 实例化Redis
$redis = new Redis();
if (is_null($redis)) {
    exit('Redis Create Failure!');
}
try {
    $redis->pconnect('127.0.0.1', 6379);
} catch (Exception $ex) {
    exit('Redis Connect Failure:' . $ex->getMessage());
}
load($redis);
$link = db_conn();
while (true) {
    main($redis);
    sleep(1);
}
mysql_close($link);
$redis->close();

function main($redis) {
    $time = date('H:i:s');
    echo PHP_EOL . 'main ' . $time;
    $w = date('w');
    if ($w < 1) {
        $w = 7;
    }
    $sw = ',' . $w . ',';
    $keys = $redis->keys('tstimer_*');
    foreach ($keys as $key) {
        $conf = $redis->hGetAll($key);
        // 判断是否启动
        if (!$conf['timer_status']) {
            continue;
        }
        // 判断工作日
        if (false === strpos((',' . $conf['timer_workday'] . ','), $sw)) {
            echo PHP_EOL . 'Today not in workday[' . $conf['timer_workday'] . '].';
            continue;
        }
        // 判断开始时间
        $starttime = $conf['timer_starttime'] . ':00';
        if ($starttime == $time) {
            echo PHP_EOL . 'Start tasks of strategy (' . $conf['id'] . ',0,1) at ' . $starttime;
            mysql_query('update tcti_task set state=1 where taskStrategyID=' . $conf['id'] . ' and unCallCount>0');
            sofn_socket_send($conf['id'] . ',0,1');
            continue;
        }
        // 判断结束时间
        $stoptime = $conf['timer_stoptime'] . ':00';
        if ($stoptime == $time) {
            echo PHP_EOL . 'Stop tasks of strategy (' . $conf['id'] . ',0,0) at ' . $stoptime;
            mysql_query('update tcti_task set state=0 where taskStrategyID=' . $conf['id']);
            sofn_socket_send($conf['id'] . ',0,0');
            continue;
        }
    }
}

function load($redis) {
    echo PHP_EOL . 'load ' . date('H:i:s');
    $source = '/var/www/html/LSR/StrategyTimer/Ready';
    if (!is_dir($source)) {
        return;
    }
    echo '.';
    if ($handle = opendir($source)) {
        while (false !== ( $f = readdir($handle) )) {
            if ('.' == $f || '..' == $f) {
                continue;
            }
            echo PHP_EOL . 'Into file ' . $f;
            $filename = $source . '/' . $f;
            if (file_exists($filename)) {
                echo '.';
                $conf = include $filename;
                $redis->hMset('tstimer_' . $conf['id'], $conf);
            }
        }
        closedir($handle);
    }
}

// ==================函数============================
/**
 * 发送sokcet数据
 * @param string $in
 * @param string $ip
 * @param int $port
 * @return string
 * @since 1.0 2014-08-14 by kerry
 * @example socket_send($tsid . ',' . $state)
 */
function sofn_socket_send($in, $ip = '', $port = 8855) {
    if (!$ip) {
        //$ip = $_SERVER['SERVER_NAME'];
        $ip = '127.0.0.1';
    }
    error_reporting(E_ALL);
    $fp = stream_socket_client("udp://$ip:$port", $errno, $errstr);
// echo 'stream_socket_client("udp://'.$ip.':'.$port.'", $errno, $errstr)';
    if (!$fp) {
        echo PHP_EOL . "ERROR: $errno - $errstr";
    } else {
        fwrite($fp, $in);
        echo PHP_EOL . fread($fp, 26);
        fclose($fp);
    }
}

function db_conn() {
    global $config;
    if (!isset($config) || !$config) {
        echo PHP_EOL . 'Database config is invalid.';
        exit;
    }
    $link = mysql_connect($config['DB_HOST'], $config['DB_USER'], $config['DB_PWD']);
    if (false === $link) {
        echo PHP_EOL . 'Database connect fail:' . mysql_error();
        mysql_close($link);
        exit;
    }
    mysql_query('set names UTF8');
    mysql_select_db($config['DB_NAME']);
    return $link;
}

/**
 * 执行MySQL语句
 * @global array $config
 * @param string $sql
 * @since 1.0 <2015-4-8> SoChishun Added.
 */
function db_execute($sql) {
    $link = db_conn();
    $result = mysql_query($sql, $link);
    if (false === $result) {
        echo PHP_EOL . 'DB execute fail:' . mysql_error();
        mysql_close($link);
        exit;
    }
    mysql_close($link);
}
